{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/bitkira/Colab/blob/main/tutorial_notebooks_zh/first_workflow.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install git+https://github.com/EvoAgentX/EvoAgentX.git"
      ],
      "metadata": {
        "id": "erGOuxRypWG0"
      },
      "id": "erGOuxRypWG0",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install PyPDF2 selenium html2text fastmcp"
      ],
      "metadata": {
        "id": "AdAxlixJpaYF"
      },
      "id": "AdAxlixJpaYF",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "3782ba2d",
      "metadata": {
        "id": "3782ba2d"
      },
      "source": [
        "# 构建你的第一个工作流\n",
        "\n",
        "在 EvoAgentX 中，工作流允许多个代理按顺序协作完成复杂任务。本教程将指导你创建和使用工作流：\n",
        "\n",
        "1. **理解顺序工作流**：学习工作流如何将多个任务连接在一起\n",
        "2. **构建顺序工作流**：创建一个包含规划和编码步骤的工作流\n",
        "3. **执行和管理工作流**：使用特定输入运行工作流\n",
        "\n",
        "通过本教程，你将能够创建顺序工作流，协调多个代理来解决复杂问题。\n",
        "\n",
        "## 1. 理解顺序工作流\n",
        "\n",
        "EvoAgentX 中的工作流代表一系列可以由不同代理执行的任务。最简单的工作流是顺序工作流，其中任务一个接一个地执行，前一个任务的输出作为后续任务的输入。\n",
        "\n",
        "让我们从导入必要的组件开始：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "7ff89b66",
      "metadata": {
        "id": "7ff89b66"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from dotenv import load_dotenv\n",
        "from evoagentx.workflow import SequentialWorkFlowGraph, WorkFlow\n",
        "from evoagentx.agents import AgentManager\n",
        "from evoagentx.models import OpenAILLMConfig, OpenAILLM\n",
        "\n",
        "try:\n",
        "    from google.colab import userdata\n",
        "    OPENAI_API_KEY = userdata.get(\"OPENAI_API_KEY\")\n",
        "except ImportError:\n",
        "    OPENAI_API_KEY = None\n",
        "\n",
        "if not OPENAI_API_KEY:\n",
        "    load_dotenv()\n",
        "    OPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1ae95285",
      "metadata": {
        "id": "1ae95285"
      },
      "source": [
        "\n",
        "## 2. 构建顺序工作流\n",
        "\n",
        "顺序工作流由一系列任务组成，每个任务都有：\n",
        "\n",
        "- 名称和描述\n",
        "- 输入和输出定义\n",
        "- 提示模板\n",
        "- 解析模式和函数（可选）\n",
        "\n",
        "以下是如何构建一个包含规划和编码任务的顺序工作流：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8b5d7018",
      "metadata": {
        "id": "8b5d7018"
      },
      "outputs": [],
      "source": [
        "# Configure the LLM\n",
        "llm_config = OpenAILLMConfig(model=\"gpt-4o-mini\", openai_key=OPENAI_API_KEY, stream=True, output_response=True)\n",
        "llm = OpenAILLM(llm_config)\n",
        "\n",
        "# Define a custom parsing function (if needed)\n",
        "from evoagentx.core.registry import register_parse_function\n",
        "from evoagentx.core.module_utils import extract_code_blocks\n",
        "\n",
        "# [optional] Define a custom parsing function (if needed)\n",
        "# It is suggested to use the `@register_parse_function` decorator to register a custom parsing function, so the workflow can be saved and loaded correctly.\n",
        "\n",
        "@register_parse_function\n",
        "def custom_parse_func(content: str) -> str:\n",
        "    return {\"code\": extract_code_blocks(content)[0]}\n",
        "\n",
        "# Define sequential tasks\n",
        "tasks = [\n",
        "    {\n",
        "        \"name\": \"Planning\",\n",
        "        \"description\": \"Create a detailed plan for code generation\",\n",
        "        \"inputs\": [\n",
        "            {\"name\": \"problem\", \"type\": \"str\", \"required\": True, \"description\": \"Description of the problem to be solved\"},\n",
        "        ],\n",
        "        \"outputs\": [\n",
        "            {\"name\": \"plan\", \"type\": \"str\", \"required\": True, \"description\": \"Detailed plan with steps, components, and architecture\"}\n",
        "        ],\n",
        "        \"prompt\": \"You are a software architect. Your task is to create a detailed implementation plan for the given problem.\\n\\nProblem: {problem}\\n\\nPlease provide a comprehensive implementation plan including:\\n1. Problem breakdown\\n2. Algorithm or approach selection\\n3. Implementation steps\\n4. Potential edge cases and solutions\",\n",
        "        \"parse_mode\": \"str\",\n",
        "        # \"llm_config\": specific_llm_config # if you want to use a specific LLM for a task, you can add a key `llm_config` in the task dict.\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"Coding\",\n",
        "        \"description\": \"Implement the code based on the implementation plan\",\n",
        "        \"inputs\": [\n",
        "            {\"name\": \"problem\", \"type\": \"str\", \"required\": True, \"description\": \"Description of the problem to be solved\"},\n",
        "            {\"name\": \"plan\", \"type\": \"str\", \"required\": True, \"description\": \"Detailed implementation plan from the Planning phase\"},\n",
        "        ],\n",
        "        \"outputs\": [\n",
        "            {\"name\": \"code\", \"type\": \"str\", \"required\": True, \"description\": \"Implemented code with explanations\"}\n",
        "        ],\n",
        "        \"prompt\": \"You are a software developer. Your task is to implement the code based on the provided problem and implementation plan.\\n\\nProblem: {problem}\\nImplementation Plan: {plan}\\n\\nPlease provide the implementation code with appropriate comments.\",\n",
        "        \"parse_mode\": \"custom\",\n",
        "        \"parse_func\": custom_parse_func\n",
        "    }\n",
        "]\n",
        "\n",
        "# Create the sequential workflow graph\n",
        "graph = SequentialWorkFlowGraph(\n",
        "    goal=\"Generate code to solve programming problems\",\n",
        "    tasks=tasks\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "759e071a",
      "metadata": {
        "id": "759e071a"
      },
      "source": [
        "\n",
        "> **Note**\n",
        ">\n",
        "> 当你使用任务列表创建 `SequentialWorkFlowGraph` 时，框架会为每个任务创建一个 `CustomizeAgent`。工作流中的每个任务都成为一个专门的代理，配置有你定义的特定提示、输入/输出格式和解析模式。这些代理按顺序连接，一个代理的输出成为下一个代理的输入。\n",
        ">\n",
        "> `parse_mode` 控制如何将 LLM 的输出解析为结构化格式。可用选项有：[`'str'`（默认）、`'json'`、`'title'`、`'xml'`、`'custom'`]。有关解析模式和示例的详细信息，请参阅 [CustomizeAgent 文档](../modules/customize_agent.md#parsing-modes)。\n",
        "\n",
        "## 3. 执行和管理工作流\n",
        "\n",
        "一旦你创建了工作流图，你就可以创建工作流实例并执行它：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "983482f1",
      "metadata": {
        "id": "983482f1"
      },
      "outputs": [],
      "source": [
        "import nest_asyncio\n",
        "nest_asyncio.apply()\n",
        "\n",
        "# Create agent manager and add agents from the workflow. It will create a `CustomizeAgent` for each task in the workflow.\n",
        "agent_manager = AgentManager()\n",
        "agent_manager.add_agents_from_workflow(\n",
        "    graph,\n",
        "    llm_config=llm_config  # This config will be used for all tasks without `llm_config`.\n",
        ")\n",
        "\n",
        "# Create workflow instance\n",
        "workflow = WorkFlow(graph=graph, agent_manager=agent_manager, llm=llm)\n",
        "\n",
        "# Execute the workflow with inputs\n",
        "output = workflow.execute(\n",
        "    inputs = {\n",
        "        \"problem\": \"Write a function to find the longest palindromic substring in a given string.\"\n",
        "    }\n",
        ")\n",
        "\n",
        "print(\"Workflow completed!\")\n",
        "print(\"Workflow output:\\n\", output)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b35a2aa7",
      "metadata": {
        "id": "b35a2aa7"
      },
      "source": [
        "\n",
        "你应该在 `execute` 方法的 `inputs` 参数中指定工作流所需的所有输入。\n",
        "\n",
        "有关完整的工作示例，请参考 [顺序工作流示例](https://github.com/EvoAgentX/EvoAgentX/blob/main/examples/sequential_workflow.py)。\n",
        "\n",
        "## 4. 保存和加载工作流\n",
        "\n",
        "你可以保存工作流图以供将来使用：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b8fce710",
      "metadata": {
        "id": "b8fce710"
      },
      "outputs": [],
      "source": [
        "# Save the workflow graph to a file\n",
        "graph.save_module(\"examples/output/saved_sequential_workflow.json\")\n",
        "\n",
        "# Load the workflow graph from a file\n",
        "loaded_graph = SequentialWorkFlowGraph.from_file(\"examples/output/saved_sequential_workflow.json\")\n",
        "\n",
        "# Create a new workflow with the loaded graph\n",
        "new_workflow = WorkFlow(graph=loaded_graph, agent_manager=agent_manager, llm=llm)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bee5a6ca",
      "metadata": {
        "id": "bee5a6ca"
      },
      "source": [
        "\n",
        "有关更复杂的工作流或不同类型的工作流图，请参阅 [工作流图](../modules/workflow_graph.md) 文档和 [动作图](../modules/action_graph.md) 文档。"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "include_colab_link": true
    },
    "language_info": {
      "name": "python"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}